#!/usr/bin/env python
#coding:utf-8
import tornado.gen
import tornado.web
from .baseHandler import BaseHandler
from bson import ObjectId
from tornado import escape


class DrugSearchHandler(BaseHandler):

    #初始化访问，返回药品列表，若跟上分页参数则，返回页面
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self,page):
        #该参数为每页显示的数量
        db = self.settings['db']
        pageCount = 20
        list = []
        #这种返回会带上总数，是为了方便前台做分页处理
        count = yield db.drug.find().count()
        try:
            if page is None:
                find_info = yield db.drug.find().limit(pageCount).skip(0).to_list(20)
                list.append(self.find_formart(find_info))
            else:
                find_info = yield db.drug.find().limit(pageCount).skip((int(page)-1)*pageCount).to_list(20)
                list.append(self.find_formart(find_info))

        except Exception:
            list.append({'error':'暂无信息'})
            self.status = 404
            self.msg = Exception
        self.response_msg(self.status,self.msg,list,count)


    #处理post搜索请求
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def post(self, *args):
        self.set_header('Access-Control-Allow-Origin','http://cmf.com:8888')
        db = self.settings['db']
        list = []
        #可以一次获取多个参数的做法
        # conditions = self.get_arguments('key[]')
        # for con in conditions:
        #     condition[con] = con[vaules]
        #先获取表单提交过来的数据
        name = self.get_argument('name') #药品名字
        license_number = self.get_argument('license_number')#批准文号
        product_name = self.get_argument('product_name')#商品名字
        # en_name = self.get_argument('en_name')#英文或拼音名字
        product_factory = self.get_argument('product_factory')#生产企业
        drug_form = self.get_argument('drug_form')#剂型
        spec = self.get_argument('spec')#规格
        root_code = self.get_argument('root_code')

        #组装查询条件
        condition = {}
        if name != '':
            condition['name'] = {'$regex': name}
        if license_number != '':
            condition['license_number'] = license_number
        if product_name != '':
            condition['product_name'] = {'$regex': product_name }
        # if en_name != '':
        #     condition['en_name'] = {'$regex': en_name }
        if product_factory != '':
            condition['product_factory'] =  {'$regex': product_factory}
        if drug_form != '':
            condition['drug_form'] = {'$regex': drug_form }
        if spec != '':
            condition['spec'] = {'$regex': spec }
        if root_code != '':
            condition['root_code'] = {'$regex': root_code }

        #组装完毕，进行查询
        try:
            find_info = yield db.drug.find(condition).to_list(20)
            count = yield db.drug.find(condition).count()
            list.append(self.find_formart(find_info))
        except Exception:
            list.append({'error':'暂无信息'})
            self.status = 404
            self.msg = '暂无信息'
        self.response_msg(self.status,self.msg,list,count)


#获取列表的内容
class CategoryHandler(BaseHandler):
    #根据分类名称获取分类下药品信息
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    #第一个参数为分类类型 第二个为分页数 第三个为主分类名 第四个为详细分类
    def get(self,input):
        pass


    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def post(self,type,p):
        #p为1是子分类，0为主
        self.set_header('Access-Control-Allow-Origin','http://cmf.com:8888')
        db = self.settings['db']
        pageCount = 20
        main = self.get_argument('main_cate')
        detail = self.get_argument('detail_cate')
        if main is None:
            self.response_msg(404,'please give me name')
        else:
            list = []
            try:
                #先通过分类的id获取到分类的名字
                if int(type) == 1:#表示是子分类
                    #根据名称获取药品名称和数量
                    find_info_cate = yield db.drug.find({'cate.main_cate':main,'cate.detail_cate':detail}).limit(pageCount).skip((int(p)-1)*pageCount).to_list(20)
                    list.append(self.find_formart(find_info_cate))
                    count = yield db.drug.find({'cate.main_cate':main,'cate.detail_cate':detail}).count()
                else:
                    #根据名称获取药品名称和数量
                    find_info_cate = yield db.drug.find({'cate.main_cate':main}).limit(pageCount).skip((int(p)-1)*pageCount).to_list(20)
                    list.append(self.find_formart(find_info_cate))
                    count = yield db.drug.find({'cate.main_cate':main}).count()
            except Exception:
                self.status = 404
                self.msg = "not fount category"
                count = 0
            self.response_msg(self.status,self.msg,list,count)



#获取分类列表
class CategoryListHandler(BaseHandler):
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self, *args, **kwargs):
        db = self.settings['db']
        list = []
        cate = yield db.category.find().to_list(20)
        list.append(self.find_formart(cate))
        self.response_msg(self.status,self.msg,list)

#获取药品详情
class DrugDetailHandler(BaseHandler):
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self,objectId):
        db = self.settings['db']
        if objectId is None or len(objectId)%12 != 0 :
            self.response_msg(404,'Your request url is illigal')
        else:
            drugInfo = yield db.drug.find({'_id':ObjectId(objectId)}).to_list(1);
            drugInfo = self.find_formart(drugInfo)
            if drugInfo:
                self.response_msg(200,'ok',drugInfo[0])
            else:
                self.response_msg(404,'No Drug Info')


